<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>诊断记录管理</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .container {
      max-width: 1200px;
      margin-top: 20px;
    }
    .table-responsive {
      margin-top: 20px;
    }
    .btn-group {
      margin-bottom: 15px;
    }
    .modal-header {
      background-color: #f8f9fa;
    }
  </style>
</head>
<body>
<div class="container">
  <h2 class="text-center mb-4">诊断记录管理</h2>

  <!-- 搜索和操作区域 -->
  <div class="row mb-3">
    <div class="col-md-6">
      <div class="input-group">
        <input type="text" id="searchInput" class="form-control" placeholder="输入症状或诊断结果搜索...">
        <button class="btn btn-outline-secondary" type="button" onclick="searchDiagnosis()">搜索</button>
      </div>
    </div>
    <div class="col-md-6 text-end">
      <button class="btn btn-primary" onclick="showAddModal()">新增诊断记录</button>
    </div>
  </div>

  <!-- 诊断记录表格 -->
  <div class="table-responsive">
    <table class="table table-striped table-hover">
      <thead class="table-dark">
      <tr>
        <th>ID</th>
        <th>预约ID</th>
        <th>患者ID</th>
        <th>医生ID</th>
        <th>症状描述</th>
        <th>诊断结果</th>
        <th>处方</th>
        <th>创建时间</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody id="diagnosisTable">
      <!-- 数据会通过JavaScript动态填充 -->
      </tbody>
    </table>
  </div>

  <!-- 分页 -->
  <nav>
    <ul class="pagination justify-content-center" id="pagination">
      <!-- 分页按钮会通过JavaScript动态生成 -->
    </ul>
  </nav>
</div>

<!-- 新增/编辑模态框 -->
<div class="modal fade" id="diagnosisModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalTitle">新增诊断记录</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="diagnosisForm">
          <input type="hidden" id="diagnosisId">
          <div class="row mb-3">
            <div class="col-md-4">
              <label class="form-label">预约ID</label>
              <input type="number" class="form-control" id="appointmentId" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">患者ID</label>
              <input type="number" class="form-control" id="patientId" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">医生ID</label>
              <input type="number" class="form-control" id="doctorId" required>
            </div>
          </div>
          <div class="mb-3">
            <label class="form-label">症状描述</label>
            <textarea class="form-control" id="symptoms" rows="3" required></textarea>
          </div>
          <div class="mb-3">
            <label class="form-label">诊断结果</label>
            <input type="text" class="form-control" id="diagnosisResult" required>
          </div>
          <div class="mb-3">
            <label class="form-label">处方信息</label>
            <textarea class="form-control" id="prescription" rows="3" required></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" onclick="saveDiagnosis()">保存</button>
      </div>
    </div>
  </div>
</div>

<!-- 引入Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
  let currentPage = 1;
  const pageSize = 10;
  let currentKeyword = '';

  // 页面加载时获取数据
  document.addEventListener('DOMContentLoaded', function() {
    loadDiagnosisData();
  });

  // 搜索诊断记录
  function searchDiagnosis() {
    currentKeyword = document.getElementById('searchInput').value.trim();
    loadDiagnosisData(1);
  }

  // 加载诊断数据
  function loadDiagnosisData(page = 1) {
    currentPage = page;

    // 构建URL，包含搜索关键词
    let url = `/api/diagnoses?current=${page}&page=${pageSize}`;
    if (currentKeyword) {
      url += `&keyword=${encodeURIComponent(currentKeyword)}`;
    }

    fetch(url)
            .then(response => {
              if (!response.ok) {
                throw new Error('网络响应不正常');
              }
              return response.json();
            })
            .then(data => {
              console.log('API返回数据:', data); // 调试用
              if (data.code === 200) {
                renderTable(data.data.records);
                renderPagination(data.data.total, page);
              } else {
                alert('加载数据失败: ' + data.msg);
              }
            })
            .catch(error => {
              console.error('Error:', error);
              alert('网络错误，请稍后重试: ' + error.message);
            });
  }

  // 渲染表格数据
  function renderTable(records) {
    const tbody = document.getElementById('diagnosisTable');
    tbody.innerHTML = '';

    if (records.length === 0) {
      tbody.innerHTML = '<tr><td colspan="9" class="text-center">暂无数据</td></tr>';
      return;
    }

    records.forEach(item => {
      const row = document.createElement('tr');
      row.innerHTML = `
        <td>${item.id || ''}</td>
        <td>${item.appointmentId}</td>
        <td>${item.patientId}</td>
        <td>${item.doctorId}</td>
        <td>${item.symptoms}</td>
        <td>${item.diagnosisResult}</td>
        <td>${item.prescription}</td>
        <td>${item.createTime ? new Date(item.createTime).toLocaleString() : ''}</td>
        <td>
          <button class="btn btn-sm btn-warning" onclick="editDiagnosis(${item.id})">编辑</button>
        </td>
      `;
      tbody.appendChild(row);
    });
  }

  // 渲染分页
  function renderPagination(total, currentPage) {
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';

    const totalPages = Math.ceil(total / pageSize);

    // 上一页
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `<a class="page-link" href="#" onclick="loadDiagnosisData(${currentPage - 1})">上一页</a>`;
    pagination.appendChild(prevLi);

    // 页码
    for (let i = 1; i <= totalPages; i++) {
      const li = document.createElement('li');
      li.className = `page-item ${i === currentPage ? 'active' : ''}`;
      li.innerHTML = `<a class="page-link" href="#" onclick="loadDiagnosisData(${i})">${i}</a>`;
      pagination.appendChild(li);
    }

    // 下一页
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
    nextLi.innerHTML = `<a class="page-link" href="#" onclick="loadDiagnosisData(${currentPage + 1})">下一页</a>`;
    pagination.appendChild(nextLi);
  }

  // 显示新增模态框
  function showAddModal() {
    document.getElementById('modalTitle').textContent = '新增诊断记录';
    document.getElementById('diagnosisForm').reset();
    document.getElementById('diagnosisId').value = '';

    const modal = new bootstrap.Modal(document.getElementById('diagnosisModal'));
    modal.show();
  }

  // 编辑诊断记录
  function editDiagnosis(id) {
    // 先加载所有数据找到要编辑的记录
    fetch(`/api/diagnoses?current=1&page=1000`)
            .then(response => response.json())
            .then(data => {
              if (data.code === 200) {
                const record = data.data.records.find(item => item.id === id);
                if (record) {
                  document.getElementById('modalTitle').textContent = '编辑诊断记录';
                  document.getElementById('diagnosisId').value = record.id;
                  document.getElementById('appointmentId').value = record.appointmentId;
                  document.getElementById('patientId').value = record.patientId;
                  document.getElementById('doctorId').value = record.doctorId;
                  document.getElementById('symptoms').value = record.symptoms;
                  document.getElementById('diagnosisResult').value = record.diagnosisResult;
                  document.getElementById('prescription').value = record.prescription;

                  const modal = new bootstrap.Modal(document.getElementById('diagnosisModal'));
                  modal.show();
                }
              }
            });
  }

  // 保存诊断记录（新增或更新）
  function saveDiagnosis() {
    const formData = {
      appointmentId: parseInt(document.getElementById('appointmentId').value),
      patientId: parseInt(document.getElementById('patientId').value),
      doctorId: parseInt(document.getElementById('doctorId').value),
      symptoms: document.getElementById('symptoms').value,
      diagnosisResult: document.getElementById('diagnosisResult').value,
      prescription: document.getElementById('prescription').value
    };

    const diagnosisId = document.getElementById('diagnosisId').value;
    const url = diagnosisId ? `/api/diagnoses/${diagnosisId}` : '/api/diagnoses';
    const method = diagnosisId ? 'PUT' : 'POST';

    console.log('发送数据:', formData); // 调试用

    fetch(url, {
      method: method,
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData)
    })
            .then(response => {
              if (!response.ok) {
                throw new Error('网络响应不正常');
              }
              return response.json();
            })
            .then(data => {
              console.log('保存响应:', data); // 调试用
              if (data.code === 200) {
                alert(data.msg);
                // 关闭模态框
                bootstrap.Modal.getInstance(document.getElementById('diagnosisModal')).hide();
                // 重新加载数据
                loadDiagnosisData(currentPage);
              } else {
                alert('操作失败: ' + data.msg);
              }
            })
            .catch(error => {
              console.error('Error:', error);
              alert('网络错误，请稍后重试: ' + error.message);
            });
  }
</script>
</body>
</html>